package com.echo.tsxStudy.soleDemo;

import java.sql.Connection;
import java.sql.SQLException;


import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;


/***
 * 想用单例模式 获取数据源连接池  
 * 不需要每次都重新获取databases connection  节约资源
 * 
 * @author tangsixiang
 *  JVM 
 */
public class JdbcDataSourceUtil {
 
/***
 * dataSourceUtil 在项目的一个生命周期内 仅仅初始化一次
 */
 private  static  JdbcDataSourceUtil dataSourceUtil;
 
  private   HikariDataSource hds;
	
  public JdbcDataSourceUtil() {
	  initDataSource();
	  System.out.println("------数据库连接被初始化了 ---");
    }
   public static  JdbcDataSourceUtil  getJdbcDataSourceUtilInstance(){
	   if(dataSourceUtil==null){
		   synchronized (JdbcDataSourceUtil.class) {
			   if(dataSourceUtil==null){
				   dataSourceUtil= new JdbcDataSourceUtil();
			   }
	   }
	}
	  
	   
	   
	   return   dataSourceUtil;
   }
	
	
	 
	public void  initDataSource() {
			synchronized (HikariDataSource.class) {
				if(hds==null){
					HikariConfig config = new HikariConfig();
					config.setMaximumPoolSize(10);
					config.setMinimumIdle(2);
					config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
					config.addDataSourceProperty("serverName", "192.168.7.133");
					config.addDataSourceProperty("port", "3306");
					config.addDataSourceProperty("databaseName", "yiwei");
					config.addDataSourceProperty("user", "root");
					config.addDataSourceProperty("password", "123456");
					//增加以下两行代码
					config.addDataSourceProperty("useUnicode", "true");
					config.addDataSourceProperty("characterEncoding", "utf8");	
					config.setConnectionTestQuery("SELECT 1");
					hds = new HikariDataSource(config);
				}	
			}
	}
	
	/***
	 * 对外提供一个数据源的 连接
	 * @return
	 * @throws SQLException
	 */
	public  Connection  getConnection() throws SQLException{
		 if(hds==null){
			 initDataSource();
		 }
		return 	hds.getConnection();
		
	}
	
}
